package service

import (
	"encoding/json"
	"errors"
	"haiqiu-go-admin/dao"
	"haiqiu-go-admin/entity"
	"haiqiu-go-admin/entity/dto"
	"haiqiu-go-admin/entity/vo"
	"haiqiu-go-admin/result"
	"haiqiu-go-admin/utils"
	"log"
	"net/http"
	"strconv"
	"time"
)

type LoginLogService struct {
}

func (LoginLogService) LoginLogPage(w http.ResponseWriter, r *http.Request) (any, error) {
	formatJson, err := utils.GetBodyFormatJson(w, r)
	if err != nil {
		return nil, errors.New(result.ParamsErr)
	}
	var page dto.LoginLogQueryDto
	err = json.Unmarshal(formatJson, &page)
	if err != nil {
		log.Println(err)
	}
	count := dao.LoginLogDao{}.LoginLogPageCount(page)
	if count == 0 {
		return vo.PageData{
			Total: 0,
		}, nil
	}
	var pageData vo.PageData
	list, err := dao.LoginLogDao{}.LoginLogPageList(page)
	pageData.Data = list
	pageData.Total = count
	pageData.PageIndex = page.PageIndex
	pageData.PageSize = page.PageSize
	if err != nil {
		return nil, err
	}
	return pageData, nil
}

func (LoginLogService) LoginLogById(w http.ResponseWriter, r *http.Request) (any, error) {
	formatJson := utils.GetParamsFormatJson(w, r)
	deptIdStr := formatJson["id"][0]
	id, err := strconv.ParseInt(deptIdStr, 10, 64)
	if err != nil {
		panic(err)
		return nil, err
	}
	data, err := dao.LoginLogDao{}.LoginLogById(id)
	if err != nil {
		return nil, err
	}
	return &data, nil
}

func (LoginLogService) LoginLogAdd(w http.ResponseWriter, r *http.Request) (any, error) {
	formatJson, err := utils.GetBodyFormatJson(w, r)
	if err != nil {
		return nil, err
	}
	var data = entity.SysLoginLog{}
	err = json.Unmarshal(formatJson, &data)
	if err != nil {
		return nil, err
	}
	var nowTime = time.Now()
	data.CreateTime = &nowTime
	data.UpdateTime = &nowTime
	row, err := dao.LoginLogDao{}.LoginLogAdd(&data)
	if err != nil {
		return nil, err
	}
	return row, nil
}

func (LoginLogService) LoginLogDeleteBatch(w http.ResponseWriter, r *http.Request) (any, error) {
	formatJson, err := utils.GetBodyFormatJson(w, r)
	if err != nil {
		return nil, err
	}
	var ids []int64
	err = json.Unmarshal(formatJson, &ids)
	if err != nil {
		return nil, err
	}

	row, err := dao.LoginLogDao{}.LoginLogDeleteBatch(ids)
	if err != nil {
		return nil, err
	}
	return row, nil
}

func (LoginLogService) LoginLogUpdate(w http.ResponseWriter, r *http.Request) (any, error) {
	formatJson, err := utils.GetBodyFormatJson(w, r)
	if err != nil {
		return nil, err
	}
	var data = entity.SysLoginLog{}
	err = json.Unmarshal(formatJson, &data)
	if err != nil {
		return nil, err
	}
	var nowTime = time.Now()
	data.UpdateTime = &nowTime
	row, err := dao.LoginLogDao{}.LoginLogUpdate(&data)
	if err != nil {
		return nil, err
	}
	return row, nil
}

func (LoginLogService) LoginLogList(w http.ResponseWriter, r *http.Request) (any, error) {
	return nil, nil
}
